package com.yiyihealth.cherriesadmin.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.date.Week;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.system.SystemUtil;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.yiyihealth.cherriesadmin.core.http.HttpResult;
import com.yiyihealth.cherriesadmin.core.page.PageRequest;
import com.yiyihealth.cherriesadmin.core.page.PageUtils;
import com.yiyihealth.cherriesadmin.core.page.Param;
import com.yiyihealth.cherriesadmin.core.smsInterface.AliyunSmsUtil;
import com.yiyihealth.cherriesadmin.core.web.BaseController;
import com.yiyihealth.cherriesadmin.model.*;
import com.yiyihealth.cherriesadmin.model.wrapper.OrdAppointmentWrapper;
import com.yiyihealth.cherriesadmin.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 预约订单记录(OrdAppointment)表控制层
 *
 * @author chen
 * @since 2020-09-25 11:00:14
 */
@Api(tags = "预约订单记录类")
@RestController
@RequestMapping("ordAppointment")
public class OrdAppointmentController extends BaseController<OrdAppointment, OrdAppointmentWrapper, Long> {
    /**
     * 服务对象
     */
    @Resource
    private OrdAppointmentService ordAppointmentService;
    @Resource
    private PubSuffererService suffererService;
    @Resource
    private PubHospitalService hospitalService;
    @Resource
    private PubPatientsService pubPatientsService;
    @Resource
    private OrdSourceDetailService sourceDetailService;
    @Resource
    private OrdSchedulingService schedulingService;
    @Resource
    private PubStaffInfoService staffInfoService;

    @Override
    @InitBinder()
    public void initBinder(WebDataBinder binder) {
        super.setBaseService(ordAppointmentService);
    }


    /**
     * 同一个患者同一个医生只能预约一个号子
     * @param record
     * @return
     */
    private String isAppointment(OrdAppointment record) throws Exception {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("sourceDetailId",record.getSourceDetailId());
        paramMap.put("appStatus","0");
        List<OrdAppointment> appointmentList = ordAppointmentService.selectList(paramMap);
        if (!CollectionUtils.isEmpty(appointmentList)){
            throw new Exception("此号已被预约 请选择其他号源！");
        }
        paramMap.clear();
        paramMap.put("schedulingId",record.getSchedulingId());
        paramMap.put("patId",record.getPatId());
        paramMap.put("appStatus","0");
        //同一个患者同一个排班下 只能预约一个号子
        appointmentList = ordAppointmentService.selectList(paramMap);
        if (!CollectionUtils.isEmpty(appointmentList)){
            OrdAppointment ordAppointment = appointmentList.get(0);
            throw new Exception("您已经预约"
                    +ordAppointment.getDepName()
                    +ordAppointment.getDoctorName()
                    +LocalDateTimeUtil.format(ordAppointment.getVisitDate(),DatePattern.CHINESE_DATE_PATTERN)
                    +ordAppointment.getVisitTime()+",第"+ordAppointment.getSerialNumber()+"号，请勿重复预约");
        }
        paramMap.clear();
        paramMap.put("schedulingId",record.getSchedulingId());
        paramMap.put("patIdentityNum",record.getPatIdentityNum());
        paramMap.put("appStatus","0");
        //同一个患者同一个排班下 只能预约一个号子
        appointmentList = ordAppointmentService.selectList(paramMap);
        if (!CollectionUtils.isEmpty(appointmentList)){
            OrdAppointment ordAppointment = appointmentList.get(0);
            throw new Exception(record.getPatName()+"您好！您已经预约"
                    +ordAppointment.getDepName()
                    +ordAppointment.getDoctorName()
                    +LocalDateTimeUtil.format(ordAppointment.getVisitDate(),DatePattern.CHINESE_DATE_PATTERN)
                    +ordAppointment.getVisitTime()+",第"+ordAppointment.getSerialNumber()+"号，请勿重复预约");
        }
        return "";
    }

    @ApiOperation(value = "号源池后台添加预约")
    @PostMapping("/createByBack")
    @ResponseBody
    public HttpResult createByBack(@RequestBody OrdAppointment record) throws Exception {
        PubSufferer pubSufferer = suffererService.selectByPrimaryKey(record.getPatId());
        if (Optional.ofNullable(pubSufferer).isPresent()){
            if (!record.getPatIdentityNum().equals(pubSufferer.getPatIdentityNum())){
                pubSufferer.setPatIdentityNum(record.getPatIdentityNum());
                suffererService.updateByPrimaryKeySelective(pubSufferer);
            }
            if (IdcardUtil.isValidCard(pubSufferer.getPatIdentityNum())){
                pubSufferer.setPatSex(IdcardUtil.getGenderByIdCard(pubSufferer.getPatIdentityNum()));
                suffererService.updateByPrimaryKeySelective(pubSufferer);
            }else {
                throw new Exception("不是有效的身份证号，请前往修改！");
            }
        }else {
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("patPhone",record.getPhone());
            List<PubPatients> patientsList = pubPatientsService.selectList(paramMap);
            if(CollectionUtils.isEmpty(patientsList)){
                PubPatients pubPatients = new PubPatients();
                pubPatients.setPatName(record.getPatName());
                pubPatients.setPatIdentityNum(record.getPatIdentityNum());
                pubPatients.setPatSex(Integer.valueOf(record.getPatSex()));
                pubPatients.setPatPhone(record.getPhone());
                pubPatients.setPassword(record.getPhone());
                pubPatientsService.insert(pubPatients);
                pubSufferer = new PubSufferer();
                pubSufferer.setPatIdentityNum(pubPatients.getPatIdentityNum());
                pubSufferer.setPatId(pubPatients.getId());
                pubSufferer.setPatName(pubPatients.getPatName());
                pubSufferer.setPatSex(pubPatients.getPatSex());
                pubSufferer.setPatPhone(pubPatients.getPatPhone());
                suffererService.insert(pubSufferer);
            }else {
                PubPatients pubPatients = patientsList.get(0);
                pubPatients.setPatSex(Integer.valueOf(record.getPatSex()));
                pubPatientsService.updateByPrimaryKeySelective(pubPatients);
                paramMap.clear();
                paramMap.put("patId",pubPatients.getId());
                paramMap.put("patIdentityNum",record.getPatIdentityNum());
                List<PubSufferer> sufferers = suffererService.selectList(paramMap);
                if (CollectionUtils.isEmpty(sufferers)){
                    pubSufferer = new PubSufferer();
                    pubSufferer.setPatIdentityNum(pubPatients.getPatIdentityNum());
                    pubSufferer.setPatId(pubPatients.getId());
                    pubSufferer.setPatName(record.getPatName());
                    pubSufferer.setPatSex(pubPatients.getPatSex());
                    pubSufferer.setPatPhone(pubPatients.getPatPhone());
                    suffererService.insert(pubSufferer);
                }else {
                    pubSufferer = sufferers.get(0);
                    pubSufferer.setPatIdentityNum(pubPatients.getPatIdentityNum());
                    pubSufferer.setPatId(pubPatients.getId());
                    pubSufferer.setPatName(record.getPatName());
                    pubSufferer.setPatSex(pubPatients.getPatSex());
                    pubSufferer.setPatPhone(pubPatients.getPatPhone());
                    suffererService.insert(pubSufferer);
                }
            }
        }
        record.setPatId(pubSufferer.getId());
        record.setSufferId(pubSufferer.getPatId());
        OrdSourceDetail sourceDetail = sourceDetailService.selectByPrimaryKey(record.getSourceDetailId());
        record.setSerialNumber(sourceDetail.getSerialNumber());
        record.setPatIdentityNum(pubSufferer.getPatIdentityNum());
        record.setBinId(sourceDetail.getBinId());
        record.setBinName(sourceDetail.getBinName());
        record.setDepId(sourceDetail.getDepId());
        record.setDepName(sourceDetail.getDepName());
        record.setDoctorId(sourceDetail.getDoctorId());
        record.setDoctorName(sourceDetail.getDoctorName());
        record.setSchedulingId(sourceDetail.getSchedulingId());
        record.setHospitalId(sourceDetail.getHospitalId());
        record.setVisitTime(sourceDetail.getVisitTime());
        String result ="";
        try {
            isAppointment(record);
            result = ordAppointmentService.createByBack(record);
            sendSMS(record);
        }catch (Exception e){
            return HttpResult.failure(e.getMessage());
        }
        return HttpResult.success(result);
    }






    private void sendSMS(OrdAppointment record){
        PubHospital hospital = hospitalService.selectByPrimaryKey(record.getHospitalId());
        OrdScheduling ordScheduling = schedulingService.selectByPrimaryKey(record.getSchedulingId());
        // 预约提醒---您好${patName},您已成功预约${hosName}医院${date}的${depName}门诊${doctorName}医生第${serialNumber}号，。就诊地址：${address}。咨询电话：${phone}。
        JSONObject appointmentReminder = new JSONObject();
        appointmentReminder.set("patName",record.getPatName());
        appointmentReminder.set("hosName",hospital.getHosName());
        appointmentReminder.set("date",LocalDateTimeUtil.format(record.getVisitDate(), DatePattern.NORM_DATE_PATTERN));
        appointmentReminder.set("depName", record.getDepName() );
        appointmentReminder.set("doctorName",record.getDoctorName());
        appointmentReminder.set("serialNumber",record.getSerialNumber());
        appointmentReminder.set("password",record.getPassword());
        appointmentReminder.set("address",hospital.getHosContactAddress());
        appointmentReminder.set("tip",ordScheduling.getTip()==null?"":ordScheduling.getTip());
        appointmentReminder.set("phone",hospital.getHosPhone());
        appointmentReminder.set("pim",record.getTimeState().equals(1) ? "上午" : ordScheduling.getTimeState().equals(2) ? "下午" : "夜门诊");
        AliyunSmsUtil.sendSms(record.getPhone(),"SMS_206546239",appointmentReminder.toString());
    }

    @ApiOperation(value = "预约详情查询")
    @PostMapping("/select_by_primary_key_Pat_ID")
    @ResponseBody
    public HttpResult selectByPrimaryKeypat(@RequestBody String str){
        Long patId=Long.parseLong(JSONUtil.parseObj(str).get("patId").toString());
        return  HttpResult.success(ordAppointmentService.selectByPrimaryKeypat(patId));
    }

    @ApiOperation(value = "后台取消预约")
    @PostMapping("/cancelByBack")
    @ResponseBody
    public HttpResult cancelByBack(@RequestBody OrdAppointment record) throws Exception {
        return HttpResult.success(ordAppointmentService.cancelByBack(record));
    }


    @ApiOperation(value = "H5患者预约")
    @PostMapping("/createByPatIdSourceDetailId")
    @ResponseBody
    public HttpResult createByPatIdSourceDetailId(@RequestParam Long sufferId, @RequestParam Long sourceDetailId,@RequestParam String spName) throws Exception {
        OrdAppointment record = new OrdAppointment();
        PubSufferer pubSufferer = suffererService.selectByPrimaryKey(sufferId);
        if (Optional.ofNullable(pubSufferer).isPresent()){
            if (IdcardUtil.isValidCard(pubSufferer.getPatIdentityNum())){
                pubSufferer.setPatSex(IdcardUtil.getGenderByIdCard(pubSufferer.getPatIdentityNum()));
                suffererService.updateByPrimaryKeySelective(pubSufferer);
            }else {
                throw new Exception("不是有效的身份证号，请前往修改！");
            }
        }else {
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("patPhone",record.getPhone());
            List<PubPatients> patientsList = pubPatientsService.selectList(paramMap);
            if(CollectionUtils.isEmpty(patientsList)){
                PubPatients pubPatients = new PubPatients();
                pubPatients.setPatName(record.getPatName());
                pubPatients.setPatIdentityNum(record.getPatIdentityNum());
                pubPatients.setPatSex(Integer.valueOf(record.getPatSex()));
                pubPatients.setPatPhone(record.getPhone());
                pubPatients.setPassword(record.getPhone());
                pubPatientsService.insert(pubPatients);
                pubSufferer = new PubSufferer();
                pubSufferer.setPatIdentityNum(pubPatients.getPatIdentityNum());
                pubSufferer.setPatId(pubPatients.getId());
                pubSufferer.setPatName(pubPatients.getPatName());
                pubSufferer.setPatSex(pubPatients.getPatSex());
                pubSufferer.setPatPhone(pubPatients.getPatPhone());
                suffererService.insert(pubSufferer);
            }else {
                PubPatients pubPatients = patientsList.get(0);
                pubPatients.setPatSex(Integer.valueOf(record.getPatSex()));
                pubPatientsService.updateByPrimaryKeySelective(pubPatients);
                paramMap.clear();
                paramMap.put("patId",pubPatients.getId());
                paramMap.put("patIdentityNum",record.getPatIdentityNum());
                List<PubSufferer> sufferers = suffererService.selectList(paramMap);
                if (CollectionUtils.isEmpty(sufferers)){
                    pubSufferer = new PubSufferer();
                    pubSufferer.setPatIdentityNum(pubPatients.getPatIdentityNum());
                    pubSufferer.setPatId(pubPatients.getId());
                    pubSufferer.setPatName(pubPatients.getPatName());
                    pubSufferer.setPatSex(pubPatients.getPatSex());
                    pubSufferer.setPatPhone(pubPatients.getPatPhone());
                    suffererService.insert(pubSufferer);
                }else {
                    pubSufferer = sufferers.get(0);
                    pubSufferer.setPatIdentityNum(pubPatients.getPatIdentityNum());
                    pubSufferer.setPatId(pubPatients.getId());
                    pubSufferer.setPatName(pubPatients.getPatName());
                    pubSufferer.setPatSex(pubPatients.getPatSex());
                    pubSufferer.setPatPhone(pubPatients.getPatPhone());
                    suffererService.insert(pubSufferer);
                }
            }
        }
        OrdSourceDetail sourceDetail = sourceDetailService.selectByPrimaryKey(sourceDetailId);
        record.setPatName(pubSufferer.getPatName());
        record.setSourceDetailId(sourceDetailId);
        record.setSchedulingId(sourceDetail.getSchedulingId());
        record.setPatId(pubSufferer.getId());
        record.setSufferId(pubSufferer.getPatId());
        record.setPatIdentityNum(pubSufferer.getPatIdentityNum());
        record.setPatSex(pubSufferer.getPatSex().toString());
        record.setPhone(pubSufferer.getPatPhone());
        record.setCreateDate(LocalDate.now());
        record.setSpName(spName);
        String result="";
        try {
            isAppointment(record);
            result = ordAppointmentService.createByPatIdSourceDetailId(record,sourceDetailId);
            sendSMS(record);
        }catch (Exception e){
            return HttpResult.failure(e.getMessage());
        }
        return HttpResult.success(result);
    }

    @GetMapping("/delete")
    @ResponseBody
    public HttpResult delete(@RequestParam Long id) throws Exception {
        OrdAppointment appointment = ordAppointmentService.selectByPrimaryKey(id);
        if (!appointment.getAppStatus().equals(0) ) {
            throw new Exception("此条作废预约记录已过期,请重复操作！");
        }
        return HttpResult.success(ordAppointmentService.delete(appointment));
    }

    /**
     * H5根据用户信息查询预约记录
     * @param patId
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "H5根据用户信息查询预约记录")
    @GetMapping("/selectListByPatId")
    @ResponseBody
    public HttpResult selectListByPatId(@RequestParam Long patId) throws Exception {
        return HttpResult.success(ordAppointmentService.selectListByPatId(patId));
    }

    /**
     * H5根据用户信息查询预约记录
     * @param patId
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "H5根据用户信息查询预约记录")
    @GetMapping("/selectListBySufferId")
    @ResponseBody
    public HttpResult selectListBySufferId(@RequestParam Long patId) throws Exception {
        return HttpResult.success(ordAppointmentService.selectListBySufferId(patId));
    }

    @Override
    public HttpResult selectListWrapper(@RequestBody  Map<String, Object> map) {
        List<OrdAppointmentWrapper> ordAppointmentList = ordAppointmentService.selectListWrapper(map);
        for (OrdAppointmentWrapper ordAppointmentWrapper:ordAppointmentList){
            PubPatients patients = pubPatientsService.selectByPrimaryKey(ordAppointmentWrapper.getSufferId());
            if (Optional.ofNullable(patients).isPresent()){
                ordAppointmentWrapper.setSufferName(patients.getPatName());

                int week = ordAppointmentWrapper.getVisitDate().getDayOfWeek().getValue()+1>7?1:ordAppointmentWrapper.getVisitDate().getDayOfWeek().getValue()+1;
                PubHospital hospital = hospitalService.selectByPrimaryKey(ordAppointmentWrapper.getHospitalId());
                ordAppointmentWrapper.setHospitalIdWrapper(hospital==null?"":hospital.getHosName());
                ordAppointmentWrapper.setWeekWrapper(Week.of(week).toChinese());
                //预约状态(0已预约 1已过期 2已取号 3患者取消 4医生停诊 5后台取消)
                if (ordAppointmentWrapper.getAppStatus().equals(0)){
                    ordAppointmentWrapper.setAppStatusWrapper("待取号");
                }else  if (ordAppointmentWrapper.getAppStatus().equals(1)){
                    ordAppointmentWrapper.setAppStatusWrapper("已过期");
                }else  if (ordAppointmentWrapper.getAppStatus().equals(2)){
                    ordAppointmentWrapper.setAppStatusWrapper("已取号");
                }else  if (ordAppointmentWrapper.getAppStatus().equals(3)){
                    ordAppointmentWrapper.setAppStatusWrapper("患者取消");
                }else  if (ordAppointmentWrapper.getAppStatus().equals(4)){
                    ordAppointmentWrapper.setAppStatusWrapper("医生停诊");
                }else  if (ordAppointmentWrapper.getAppStatus().equals(5)){
                    ordAppointmentWrapper.setAppStatusWrapper("平台取消");
                }
                if (ordAppointmentWrapper.getTimeState().equals(1)){
                    ordAppointmentWrapper.setTimeStateWrapper("上午");
                }else if (ordAppointmentWrapper.getTimeState().equals(2)){
                    ordAppointmentWrapper.setTimeStateWrapper("下午");
                }else if (ordAppointmentWrapper.getTimeState().equals(3)){
                    ordAppointmentWrapper.setTimeStateWrapper("夜门诊");
                }
            }

        }
        return HttpResult.success(ordAppointmentList);
    }



    @Override
    public HttpResult selectListWrapperPage(@RequestBody PageRequest pageRequest) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        Map<String, Object> map = new HashMap<>();
        for (Param param:pageRequest.getParams()){
            if (!StrUtil.isBlank(param.getValue())){
                map.put(param.getName(),param.getValue());
            }
        }
        PageInfo<OrdAppointmentWrapper> pageInfo = ordAppointmentService.selectListWrapperPage(map,pageNum,pageSize);
        List<OrdAppointmentWrapper> ordAppointmentWrappers = pageInfo.getList();
        for (OrdAppointmentWrapper ordAppointmentWrapper:ordAppointmentWrappers){
            PubPatients patients = pubPatientsService.selectByPrimaryKey(ordAppointmentWrapper.getSufferId());
            if (Optional.ofNullable(patients).isPresent()){
                ordAppointmentWrapper.setSufferName(patients.getPatName());
            }
            if (Optional.ofNullable(ordAppointmentWrapper.getSffId()).isPresent()){
                PubStaffInfo pubStaffInfo = staffInfoService.selectByPrimaryKey(ordAppointmentWrapper.getSffId());
                ordAppointmentWrapper.setSffName(pubStaffInfo.getSffName());
            }
            if (Optional.ofNullable(ordAppointmentWrapper.getCancelSffId()).isPresent()){
                PubStaffInfo pubStaffInfo = staffInfoService.selectByPrimaryKey(ordAppointmentWrapper.getCancelSffId());
                ordAppointmentWrapper.setCancelSffName(pubStaffInfo.getSffName());
            }
        }
        ordAppointmentWrappers.stream().sorted(Comparator.comparing(OrdAppointment::getCreateDate)).collect(Collectors.toList());
        pageInfo.setList(ordAppointmentWrappers);
        return HttpResult.success(PageUtils.getPageResult(pageRequest,pageInfo));
    }

    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @PostMapping("/download")
    @ResponseBody
    public HttpResult download(@RequestBody PageRequest pageRequest) throws Exception {
        Map<String, Object> map = new HashMap<>();
        for (Param param:pageRequest.getParams()){
            if (!StrUtil.isBlank(param.getValue())){
                map.put(param.getName(),param.getValue());
            }
        }
        List<OrdAppointmentWrapper> ordAppointmentWrappers =  ordAppointmentService.selectListWrapper(map);
        for (OrdAppointmentWrapper appointment:ordAppointmentWrappers){
            int week = appointment.getVisitDate().getDayOfWeek().getValue()+1>7?1:appointment.getVisitDate().getDayOfWeek().getValue()+1;
            PubHospital hospital = hospitalService.selectByPrimaryKey(appointment.getHospitalId());
            appointment.setHospitalIdWrapper(hospital==null?"":hospital.getHosName());
            appointment.setWeekWrapper(Week.of(week).toChinese());
            //预约状态(0已预约 1已过期 2已取号 3患者取消 4医生停诊 5后台取消)
            if (appointment.getAppStatus().equals(0)){
                appointment.setAppStatusWrapper("待取号");
            }else  if (appointment.getAppStatus().equals(1)){
                appointment.setAppStatusWrapper("已过期");
            }else  if (appointment.getAppStatus().equals(2)){
                appointment.setAppStatusWrapper("已取号");
            }else  if (appointment.getAppStatus().equals(3)){
                appointment.setAppStatusWrapper("患者取消");
            }else  if (appointment.getAppStatus().equals(4)){
                appointment.setAppStatusWrapper("医生停诊");
            }else  if (appointment.getAppStatus().equals(5)){
                appointment.setAppStatusWrapper("平台取消");
            }
            if (appointment.getTimeState().equals(1)){
                appointment.setTimeStateWrapper("上午");
            }else if (appointment.getTimeState().equals(2)){
                appointment.setTimeStateWrapper("下午");
            }else if (appointment.getTimeState().equals(3)){
                appointment.setTimeStateWrapper("夜门诊");
            }
            if (Optional.ofNullable(appointment.getSffId()).isPresent()){
                PubStaffInfo pubStaffInfo = staffInfoService.selectByPrimaryKey(appointment.getSffId());
                appointment.setSffName(pubStaffInfo.getSffName());
            }
            if (Optional.ofNullable(appointment.getCancelSffId()).isPresent()){
                PubStaffInfo pubStaffInfo = staffInfoService.selectByPrimaryKey(appointment.getCancelSffId());
                appointment.setCancelSffName(pubStaffInfo.getSffName());
            }
        }
        String fileName="";
        String fileNameTemp = "预约订单记录" + LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.CHINESE_DATE_TIME_PATTERN) + ".xls";
        if (SystemUtil.getOsInfo().isLinux()) {
            fileName = "/home/img/" + fileNameTemp;
        } else {
            fileName = "D:/test/" + fileNameTemp;
        }


        EasyExcel.write(fileName, OrdAppointmentWrapper.class).sheet("预约订单记录").doWrite(ordAppointmentWrappers);
        String url = "static/" + fileNameTemp;
        return HttpResult.success(url);
    }



    @ApiOperation(value = "统计报表")
    @PostMapping("/selectStatis")
    @ResponseBody
    public HttpResult selectStatis(@RequestBody String parma){
       String par= parma.substring(0,1);
        System.out.println(par);
        Map<String, Object> map = new HashMap<>();
       if ("1".equals(par)){
           map.put("spName","12580");
       }else if ("3".equals(par)){
           map.put("spName","诊间预约");
       }else if ("4".equals(par)){
           map.put("spName","电话预约");
       }
        return  HttpResult.success(ordAppointmentService.selectStatis(map));
    }
    @ApiOperation(value = "报表导出")
    @PostMapping("/download2")
    @ResponseBody
    public HttpResult download2(@RequestBody String parma) throws Exception{
        String par= parma.substring(0,1);
        System.out.println(par);
        Map<String, Object> map = new HashMap<>();
        String val="全部";
       if (par.equals("2")){
           val="自有平台预约";
           long[] l=new long[3];
           l[0]=57170;
           l[1]=57171;
           l[2]=57172;
           List<String> row0 = CollUtil.newArrayList(val);
           List<String> row1 = CollUtil.newArrayList("月份");
           List<String> row2 = CollUtil.newArrayList("丰谭馆");
           List<String> row3 = CollUtil.newArrayList("风起馆");
           List<String> row4 = CollUtil.newArrayList("和平馆");

           List<statis> arr= ordAppointmentService.priselectStatis(map);
           List listTemp = new ArrayList();
           for (int i=0;i<arr.size();i++){
               if(!listTemp.contains(arr.get(i).getDate())){
                   listTemp.add(arr.get(i).getDate());
               }
           }
           for (int i=0;i<listTemp.size();i++){
               String str=listTemp.get(i).toString().substring(0,7)+"月";
               row1.add(str);
           }
           for (int i=0;i<arr.size();i++){
               if (arr.get(i).getHisID()==l[0]){
                   row2.add(arr.get(i).getNum().toString());
               }else  if (arr.get(i).getHisID()==l[1]){
                   row3.add(arr.get(i).getNum().toString());
               }else  if (arr.get(i).getHisID()==l[2]){
                   row4.add(arr.get(i).getNum().toString());
               }
           }
           List<List<String>> rows = CollUtil.newArrayList(row0,row1, row2, row3, row4);
           String fileName="";
           String fileNameTemp = "预约统计报表" + LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.CHINESE_DATE_TIME_PATTERN) + ".xls";
           if (SystemUtil.getOsInfo().isLinux()) {
               fileName = "/home/img/" + fileNameTemp;
           } else {
               fileName = "D:/test/" + fileNameTemp;
           }


           EasyExcel.write(fileName).sheet("预约统计报表").doWrite(rows);
           String url = "static/" + fileNameTemp;
           return HttpResult.success(url);
        }else{

            if ("1".equals(par)){
                map.put("spName","12580");
                val="省平台预约";
            }else if ("3".equals(par)){
                map.put("spName","诊间预约");
                val="诊间预约";
            }else if ("4".equals(par)){
                map.put("spName","电话预约");
                val="电话预约";
            }
            long[] l=new long[3];
            l[0]=57170;
            l[1]=57171;
            l[2]=57172;
            List<String> row0 = CollUtil.newArrayList(val);
            List<String> row1 = CollUtil.newArrayList("月份");
            List<String> row2 = CollUtil.newArrayList("丰谭馆");
            List<String> row3 = CollUtil.newArrayList("风起馆");
            List<String> row4 = CollUtil.newArrayList("和平馆");
            List<statis> arr= ordAppointmentService.selectStatis(map);
            List listTemp = new ArrayList();
            for (int i=0;i<arr.size();i++){
                if(!listTemp.contains(arr.get(i).getDate())){
                    listTemp.add(arr.get(i).getDate());
                }
            }
            for (int i=0;i<listTemp.size();i++){
                String str=listTemp.get(i).toString().substring(0,7)+"月";
                row1.add(str);
            }
            for (int i=0;i<arr.size();i++){
                if (arr.get(i).getHisID()==l[0]){
                    row2.add(arr.get(i).getNum().toString());
                }else  if (arr.get(i).getHisID()==l[1]){
                    row3.add(arr.get(i).getNum().toString());
                }else  if (arr.get(i).getHisID()==l[2]){
                    row4.add(arr.get(i).getNum().toString());
                }
            }
            List<List<String>> rows = CollUtil.newArrayList(row0,row1, row2, row3, row4);
           String fileName="";
           String fileNameTemp = "预约统计报表" + LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.CHINESE_DATE_TIME_PATTERN) + ".xls";
           if (SystemUtil.getOsInfo().isLinux()) {
               fileName = "/home/img/" + fileNameTemp;
           } else {
               fileName = "D:/test/" + fileNameTemp;
           }


           EasyExcel.write(fileName).sheet("预约统计报表").doWrite(rows);
           String url = "static/" + fileNameTemp;
           return HttpResult.success(url);
        }

    }
    @ApiOperation(value = "自有平台统计报表")
    @PostMapping("/priselectStatis")
    @ResponseBody
    public HttpResult priselectStatis(@RequestBody String parma){
        String par= parma.substring(0,1);
        Map<String, Object> map = new HashMap<>();
        return  HttpResult.success(ordAppointmentService.priselectStatis(map));
    }


    @ApiOperation(value = "科室统计报表")
    @PostMapping("/selectStatisDepartments")
    @ResponseBody
    public HttpResult selectStatisDepartments(@RequestBody Map map){

        return  HttpResult.success(ordAppointmentService.selectStatisDepartments(map));
    }
    @ApiOperation(value = "医生预约量统计报表")
    @PostMapping("/selectStatisDoctor")
    @ResponseBody
    public HttpResult selectStatisDoctor(@RequestBody Map map){

        return  HttpResult.success(ordAppointmentService.selectStatisDoctor(map));
    }

    @ApiOperation(value = "数据中台")
    @PostMapping("/selectDataCenter")
    @ResponseBody
    public HttpResult selectDataCenter(){
        return  HttpResult.success(ordAppointmentService.selectDataCenter());
    }
    @ApiOperation(value = "数据中台")
    @PostMapping("/selectZoneDataCenter")
    @ResponseBody
    public HttpResult selectZoneDataCenter(Long hospitalId){
        return  HttpResult.success(ordAppointmentService.selectZoneDataCenterCount(hospitalId));
    }

}
